<template>
  <div class="page flex flex-col gap-y-3 p-3 h-dvh">
    <n-card :bordered="false">
      <n-form
        label-align="left"
        label-placement="left"
        label-width="auto"
        :inline="true"
        :model="formParams"
        :show-feedback="false"
        :show-require-mark="false"
      >
        <n-grid responsive="screen" cols="1 s:1 m:2 l:3 xl:4 2xl:4" :collapsed="isCollapse" :x-gap="16" :y-gap="16">
          <n-form-item-gi label="用户名称"> <n-input v-model:value="formParams.usrNm" placeholder="请输入用户名称" clearable /> </n-form-item-gi>
          <n-form-item-gi label="手机号码"> <n-input v-model:value="formParams.moblNo" placeholder="请输入手机号码" clearable /> </n-form-item-gi>
          <n-form-item-gi label="电子邮箱"> <n-input v-model:value="formParams.mailNo" placeholder="请输入电子邮箱" clearable /> </n-form-item-gi>
          <n-form-item-gi label="昵称"> <n-input v-model:value="formParams.nickNm" placeholder="请输入昵称" clearable /> </n-form-item-gi>
          <n-gi :suffix="true">
            <n-space align="center" justify="end">
              <n-button v-if="hasPermission('bmpus:usr:search', '查询用户管理列表')" type="primary" :loading="searchBtnLoading" @click="handleSearch">
                <template #icon>
                  <n-icon>
                    <SearchOutlined />
                  </n-icon>
                </template>
                查询
              </n-button>
              <n-button @click="() => (formParams = new FormParams())">重置</n-button>
              <n-button type="primary" icon-placement="right" text @click="() => (isCollapse = !isCollapse)">
                <template #icon>
                  <n-icon size="14" v-if="isCollapse">
                    <DownOutlined />
                  </n-icon>
                  <n-icon size="14" v-else>
                    <UpOutlined />
                  </n-icon>
                </template>
                {{ isCollapse ? '展开' : '收起' }}
              </n-button>
            </n-space>
          </n-gi>
        </n-grid>
      </n-form>
    </n-card>
    <n-card :bordered="false" class="flex-1">
      <DataTable
        remote
        striped
        :row-key="(row: BMPUS.UsrQryOutput_UsrDto) => row.usrId"
        :columns="tableColumns"
        :data="dataList"
        :pagination="pagination"
        :loading="dataLoading"
        :scroll-x="2500"
        @update:page="updatePage"
        @update:page-size="updatePageSize"
        @reload="loadData"
      >
        <template #title>
          <n-space align="center">
            <n-button v-if="hasPermission('bmpus:usr:add', '新增用户')" type="primary" @click="handleAdd">
              <template #icon>
                <n-icon>
                  <PlusOutlined />
                </n-icon>
              </template>
              新建
            </n-button>
          </n-space>
        </template>
      </DataTable>
      <Edit v-model:show="showModal" :biz-id="bizId" :width="600" @refresh="loadData" />
    </n-card>
  </div>
</template>

<script lang="ts" setup>
import { h, reactive, ref, onMounted } from 'vue';
import { NSpace, NTag, NAvatar, NIcon, NButton, NPopconfirm } from 'naive-ui';
import type { DataTableColumns } from 'naive-ui';
import { formatDate, removeEmptyField } from '@yanfan/common/utils';
import DataTable, { getDefaultPagination } from '@/components/DataTable';
import type * as BMPUS from '@yanfan/bmpus-tsapi/types';
import { usrQry, usrRmv } from '@yanfan/bmpus-tsapi/usr';
import { DownOutlined, UpOutlined, SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined } from '@vicons/antd';
import { usePermission } from '@yanfan/common/hooks';
import Edit from './Edit.vue';

defineOptions({
  name: 'BmpusUsrList',
  titl: '用户管理列表',
});

class FormParams {
  usrNm: string | null = null;
  moblNo: string | null = null;
  mailNo: string | null = null;
  nickNm: string | null = null;
  genderCd: string | null = null;
  birthDt: number | null = null;
  distCd: string | null = null;
  distNm: string | null = null;
  avtrUrl: string | null = null;
  persnSign: string | null = null;
  lastLoginIp: string | null = null;
  lastLoginTm: number | null = null;
  enableFlg: number | null = null;
  actvFlg: number | null = null;
  rgstFlg: number | null = null;
  delFlg: number | null = null;
  saFlg: number | null = null;
}

const tableColumns: DataTableColumns<BMPUS.UsrQryOutput_UsrDto> = [
  {
    title: '用户头像',
    key: 'avtrUrl',
    width: 100,
    render(row) {
      return h(NAvatar, { size: 48, src: row.avtrUrl });
    },
  },
  {
    title: '昵称',
    key: 'nickNm',
    width: 150,
    ellipsis: {
      tooltip: true,
    },
  },
  {
    title: '性别',
    key: 'genderCd',
    width: 100,
    render(row) {
      return h(
        NTag,
        {
          type: 'primary',
        },
        {
          default: () => (row.genderCd === '1' ? '男' : '女'),
        },
      );
    },
  },
  {
    title: '生日',
    key: 'birthDt',
    width: 120,
    render(rowData) {
      return formatDate(rowData.birthDt, 'YYYY-MM-DD');
    },
  },
  {
    title: '用户名称',
    key: 'usrNm',
    width: 150,
    ellipsis: {
      tooltip: true,
    },
  },
  { title: '手机号码', key: 'moblNo', width: 150 },
  {
    title: '电子邮箱',
    key: 'mailNo',
    width: 180,
    ellipsis: {
      tooltip: true,
    },
  },
  { title: '地区编码', key: 'distCd', width: 150 },
  {
    title: '地区名称',
    key: 'distNm',
    width: 200,
    ellipsis: {
      tooltip: true,
    },
  },
  {
    title: '个性签名',
    key: 'persnSign',
    width: 200,
    ellipsis: {
      tooltip: true,
    },
  },
  { title: '最后登录IP', key: 'lastLoginIp', width: 150 },
  {
    title: '最后登录时间',
    key: 'lastLoginTm',
    width: 180,
    render(rowData) {
      return formatDate(rowData.lastLoginTm, 'YYYY-MM-DD HH:mm:ss');
    },
  },
  { title: '启用', key: 'enableFlg', width: 100 },
  {
    title: '备注',
    key: 'rmrk',
    ellipsis: {
      tooltip: true,
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 140,
    align: 'center',
    fixed: 'right',
    render(row) {
      return h(NSpace, { align: 'center', justify: 'center' }, () => [
        h(
          NButton,
          { type: 'info', text: true, onClick: () => handleEdit(row) },
          { icon: () => h(NIcon, { size: 18 }, () => h(EditOutlined)), default: () => '编辑' },
        ),
        h(
          NPopconfirm,
          { onPositiveClick: () => handleDelete(row) },
          {
            trigger: () =>
              h(NButton, { type: 'error', text: true }, { icon: () => h(NIcon, { size: 18 }, () => h(DeleteOutlined)), default: () => '删除' }),
            default: () => '确定要删除该数据吗？',
          },
        ),
      ]);
    },
  },
];

const { hasPermission } = usePermission();
const showModal = ref(false);
const isCollapse = ref(false);
const formParams = ref(new FormParams());
const searchBtnLoading = ref(false);
const bizId = ref<string | null>(null);
const pagination = reactive(getDefaultPagination());
const dataLoading = ref(false);
const dataList = ref<BMPUS.UsrQryOutput_UsrDto[]>([]);

onMounted(() => {
  loadData();
});

function updatePage(page: number) {
  pagination.page = page;
  loadData();
}

function updatePageSize(pageSize: number) {
  pagination.page = 1;
  pagination.pageSize = pageSize;
  loadData();
}

function loadData() {
  dataLoading.value = true;
  usrQry({ pageIndx: pagination.page, pageSize: pagination.pageSize, ...removeEmptyField(formParams.value) })
    .then((data) => {
      dataList.value = data.list;
      pagination.itemCount = data.totl;
    })
    .finally(() => {
      dataLoading.value = false;
      searchBtnLoading.value = false;
    });
}

function handleSearch() {
  searchBtnLoading.value = true;
  pagination.page = 1;
  loadData();
}

function handleAdd() {
  bizId.value = String();
  showModal.value = true;
}

function handleEdit(row: BMPUS.UsrQryOutput_UsrDto) {
  bizId.value = row.usrId;
  showModal.value = true;
}

function handleDelete(row: BMPUS.UsrQryOutput_UsrDto) {
  usrRmv({ usrId: row.usrId }).then(() => {
    window.$message.success('删除成功');
    loadData();
  });
}
</script>

<style lang="scss" scoped></style>
